<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 新增投诉状态筛选 -->
      <el-form-item label="投诉状态">
        <el-select v-model="queryParams.complaintState" style="width: 180px" placeholder="请选择投诉状态" clearable>
          <el-option label="待处理" value="0" />
          <el-option label="已处理" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['LXHComplaint:LXHDocComplaint:add']"
        >我要投诉</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="success"-->
<!--            plain-->
<!--            icon="Edit"-->
<!--            :disabled="single"-->
<!--            @click="handleUpdate"-->
<!--            v-hasPermi="['LXHComplaint:LXHDocComplaint:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--            type="danger"-->
<!--            plain-->
<!--            icon="Delete"-->
<!--            :disabled="multiple"-->
<!--            @click="handleDelete"-->
<!--            v-hasPermi="['LXHComplaint:LXHDocComplaint:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['LXHComplaint:LXHDocComplaint:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="LXHDocComplaintList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
<!--      <el-table-column label="投诉ID" align="center" prop="complaintId" />-->
<!--      <el-table-column label="用户ID" align="center" prop="userId" />-->
<!--      <el-table-column label="医生ID" align="center" prop="doctorId" />-->
      <el-table-column label="医生姓名" align="center" prop="doctorName" />
      <el-table-column label="投诉原因" align="center" prop="complaintReason" />
      <el-table-column label="投诉内容" align="center" prop="complaintInfo" />
      <!-- 优化投诉状态显示 -->
      <el-table-column label="投诉状态" align="center" prop="complaintState">
        <template #default="scope">
          <el-tag v-if="scope.row.complaintState === '1'" type="warning">待处理</el-tag>
          <el-tag v-if="scope.row.complaintState === '0'" type="success">已处理</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['LXHComplaint:LXHDocComplaint:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['LXHComplaint:LXHDocComplaint:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改个人投诉对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="LXHDocComplaintRef" :model="form" :rules="rules" label-width="80px">
        <!-- 医生选择下拉框 -->
        <el-form-item label="医生" prop="doctorId">
          <el-select v-model="form.doctorId" placeholder="请选择医生" v-loading="doctorLoading" @change="handleDoctorChange">
            <el-option
                v-for="doctor in doctorList"
                :key="doctor.doctorId"
                :label="doctor.doctorName"
                :value="doctor.doctorId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="投诉原因" prop="complaintReason">
          <el-input v-model="form.complaintReason" placeholder="请输入投诉原因" />
        </el-form-item>

        <el-form-item label="投诉内容" prop="complaintInfo">
          <el-input v-model="form.complaintInfo" placeholder="请输入投诉内容" type="textarea" rows="4" />
        </el-form-item>

        <!-- 投诉状态选择 -->
<!--        <el-form-item label="投诉状态" prop="complaintState">-->
<!--          <el-select v-model="form.complaintState" placeholder="请选择投诉状态">-->
<!--            <el-option label="待处理" value="1" />-->
<!--            <el-option label="已处理" value="0" />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LXHDocComplaint">
import { getCurrentInstance } from 'vue'  // 新增：引入getCurrentInstance
import { listLXHDocComplaint, getLXHDocComplaint, delLXHDocComplaint, addLXHDocComplaint, updateLXHDocComplaint } from "@/api/LXHComplaint/LXHDocComplaint"
import { getTeamDoctors } from "@/api/LXHComplaint/doctorSelect"
import useUserStore from '@/store/modules/user'

// 初始化用户Store
const userStore = useUserStore()
// 新增：获取proxy实例（关键修复点）
const { proxy } = getCurrentInstance()

const LXHDocComplaintList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const doctorList = ref([])
const doctorLoading = ref(false)

const data = reactive({
  form: {
    complaintId: null,
    userId: null,
    doctorId: null,
    doctorName: null, // 用于存储医生姓名
    complaintReason: null,
    complaintInfo: null,
    complaintState: null
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    complaintState: null // 用于筛选
  },
  rules: {
    doctorId: [
      { required: true, message: "医生不能为空", trigger: "change" }
    ],
    complaintReason: [
      { required: true, message: "投诉原因不能为空", trigger: "blur" }
    ],
    complaintInfo: [
      { required: true, message: "投诉内容不能为空", trigger: "blur" }
    ],
    complaintState: [
      { required: true, message: "投诉状态不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询个人投诉列表 */
function getList() {
  loading.value = true
  listLXHDocComplaint(queryParams.value).then(response => {
    LXHDocComplaintList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

/** 获取团队医生列表 */
function getTeamDoctorList() {
  // 使用框架内置方法获取当前用户ID（更规范）
  const userId = userStore.userId
  doctorLoading.value = true
  getTeamDoctors(userId).then(response => {
    doctorList.value = response.data || [] // 适配接口返回格式（假设返回AjaxResult.data）
    doctorLoading.value = false
  }).catch(() => {
    doctorLoading.value = false
    proxy.$modal.msgError("获取医生列表失败")
  })
}

/** 医生选择变更时同步医生姓名 */
function handleDoctorChange(doctorId) {
  const selectedDoctor = doctorList.value.find(doctor => doctor.userId === doctorId)
  if (selectedDoctor) {
    form.value.doctorName = selectedDoctor.nickName
  } else {
    form.value.doctorName = null
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    complaintId: null,
    userId: userStore.userId, // 重置时保留当前用户ID
    doctorId: null,
    doctorName: null,
    complaintReason: null,
    complaintInfo: null,
    complaintState: null
  }
  proxy.resetForm("LXHDocComplaintRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.complaintId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  form.value.userId = userStore.userId // 使用框架用户ID
  getTeamDoctorList()
  open.value = true
  title.value = "添加个人投诉"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const complaintId = row ? row.complaintId : ids.value[0]
  getLXHDocComplaint(complaintId).then(response => {
    form.value = { ...response.data }
    // 回显医生姓名
    const doctor = doctorList.value.find(d => d.userId === form.value.doctorId)
    if (doctor) {
      form.value.doctorName = doctor.nickName
    }
    getTeamDoctorList() // 重新加载医生列表确保数据最新
    open.value = true
    title.value = "修改个人投诉"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["LXHDocComplaintRef"].validate(valid => {
    if (valid) {
      const submitFunc = form.value.complaintId ? updateLXHDocComplaint : addLXHDocComplaint
      submitFunc(form.value).then(() => {
        proxy.$modal.msgSuccess(form.value.complaintId ? "修改成功" : "新增成功")
        open.value = false
        getList()
      }).catch(() => {
        proxy.$modal.msgError(form.value.complaintId ? "修改失败" : "新增失败")
      })
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const complaintIds = row ? [row.complaintId] : ids.value
  proxy.$modal.confirm(`是否确认删除选中的${complaintIds.length}条投诉数据？`).then(() => {
    return delLXHDocComplaint(complaintIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('LXHComplaint/LXHDocComplaint/export', {
    ...queryParams.value
  }, `LXHDocComplaint_${new Date().getTime()}.xlsx`)
}

// 初始化加载列表
getList()
</script>